<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;                            
use App\Models\Scm\TransactionType AS ScmTransactionType;                  
use App\Models\Scm\ExpenseType AS ScmExpenseType;                  
use App\Models\Scm\BillType AS ScmBillType;                  
use App\Models\Scm\BizType AS ScmBizType;                   
use App\Models\Scm\Warehouse AS ScmWarehouse;                   
use App\Models\Scm\Location AS ScmLocation;      
use App\Models\Scm\Supplier AS ScmSupplier;        
use App\Models\Scm\Inbound AS ScmInbound;  
use App\Models\Scm\InboundDetail AS ScmInboundDetail;   
use App\Models\Scm\PurchaseRequisitionDetail AS ScmPurchaseRequisitionDetail;     
use App\Models\Scm\Order AS ScmOrder;   
use App\Models\Scm\UnitRelation AS ScmUnitRelation; 
use App\Models\Scm\SyncRecord AS ScmSyncRecord; 
use App\Models\Headquarters\TransactionType AS HQTransactionType;           
use App\Models\Headquarters\ExpenseType AS HQExpenseType;          
use App\Models\Headquarters\BillType AS HQBillType;           
use App\Models\Headquarters\BizType AS HQBizType;           
use App\Models\Headquarters\Warehouse AS HQWarehouse;          
use App\Models\Headquarters\Location AS HQLocation;      
use App\Models\Headquarters\Supplier AS HQSupplier;   
use App\Models\Headquarters\PurInWarehsBill AS HQInbound;  
use App\Models\Headquarters\PurInWarehsEntry AS HQInboundDetail;     
use App\Models\Headquarters\MeasureUnit AS HQMeasureUnit;  
use App\Models\Headquarters\Material AS HqMaterial;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Log;
use App\Notifications\SendEmail;
use App\Models\User;
use PDOException;
use Illuminate\Support\Facades\Http;

class InboundService
{
    protected $baseurl;
    protected $apikey;

    public function __construct()
    {
        $this->baseurl = "http://" . config('scm.host') . ":" . config('scm.port');
        $this->apikey = config('scm.apikey');
    }


    /**
     * 同步入库单
     */
    public function syncInbound($mysql_scm, $sqlsrv, $type)
    {
        try {
            $timestamp = time() - 7 * 24 * 60 * 60;
            // $startDate = "2025-11-01";
            // $timestamp = strtotime($startDate);
            $compareStartDate = date("Y-m-d H:i:s", $timestamp);
            $scmInbound = (new ScmInbound())->setConnection($mysql_scm);
            $scmSupplier = (new ScmSupplier())->setConnection($mysql_scm);
            $hqTransactionType = (new HQTransactionType())->setConnection($sqlsrv);
            $hqBizType = (new HQBizType())->setConnection($sqlsrv);
            $hqExpenseType = (new HQExpenseType())->setConnection($sqlsrv);
            $datalist = HQInbound::on($sqlsrv)->where("FCreateTime", ">=", $compareStartDate)->orWhere('FLastUpdateTime', '>=', $compareStartDate)->orderBy("FCreateTime", "DESC")->get();
        
            $insertApprovedIds = [];   //新增审核数据
            $updateApprovedIds = [];   //已审核数据更新
            $updateUnApprovedIds = []; //反审核数据更新
            $updateCanceldIds = [];    //作废数据更新
            $params = [];//插入的数据
            foreach($datalist as $row){
                //本地采购系统是否存在
                $scmSupplierRow = $scmSupplier->findRowByKingdeeId($row->FSupplierID);
                $hqTransactionTpyeRow = $hqTransactionType->findRowById($row->FTransactionTypeID);
                $hqBizTypeRow = $hqBizType->findRowById($row->FBizTypeID);
                $hqExpenseTypeRow = $row->CFRukuleibieID ? $hqExpenseType->findRowById($row->CFRukuleibieID) : null;
                $param = array(
                    'kingdee_inbound_type' => $hqExpenseTypeRow ? $hqExpenseTypeRow->FNumber : "",
                    'kingdee_contract_id' => $row->CFKDTextField,
                    'supplier_id' => $scmSupplierRow ? $scmSupplierRow->id : "",
                    'transaction_type' => $hqTransactionTpyeRow ? $hqTransactionTpyeRow->FNumber : "",
                    'kingdee_biz_type' => $hqBizTypeRow ? $hqBizTypeRow->FNumber : "",
                    'kingdee_base_status' => $row->FBaseStatus,   //新增=0,保存=1,提交=2,作废=3,审核=4,下达=5,冻结=6,关闭=7,完工=8,完成=90,发布=10,结案=11
                    'audit_time' => date("Y-m-d H:i:s", strtotime($row->FAuditTime)),
                    'kingdee_code' => $row->FNumber,
                    'last_update_time' => date("Y-m-d H:i:s", strtotime($row->FLastUpdateTime)),
                    'update_time' => date("Y-m-d H:i:s", strtotime($row->FLastUpdateTime)),
                    'create_time' => date("Y-m-d H:i:s", strtotime($row->FCreateTime)),
                    'inbound_date' => date("Y-m-d H:i:s", strtotime($row->FAuditTime)),
                    'inbound_code' => $row->FNumber,
                    'id' => $row->FID,
                    'kingdee_id' => $row->FID,
                    'sync_time' => date("Y-m-d H:i:s")
                );

                //更新状态
                if($param['kingdee_base_status'] == 3){
                    $param['is_cancel'] = 1;
                    $param['status'] = 0;
                }
                else if($param['kingdee_base_status'] == 4){
                    $param['is_cancel'] = 0;
                    $param['status'] = 2;
                }
                else{
                    $param['is_cancel'] = 0;
                    $param['status'] = 0;
                }

                //到货状态
                if($hqTransactionTpyeRow){
                    if($hqTransactionTpyeRow->FNumber == "104"){
                        $param['receive_status'] = 0;
                    }
                    else{
                        if($row->FBaseStatus == 4){
                            //审核状态
                            $param['receive_status'] = 2;
                        }
                        else{
                            $param['receive_status'] = 0; //0未入库、1部分入库、2已入库
                        }
                    }
                }

                $existObj = $scmInbound->findRowByKingdeeCode($row->FNumber);
                if(!$existObj){
                    //插入数据
                    //$scmInbound->insertOne($param);//改成批量插入数据
                    $params[] = $param;
                    if($type == 'init'){
                        //do nothing
                    }
                    else{
                        //新增同步
                        if($param['kingdee_base_status'] == 4){
                            //新增的数据、且状态为 【审核】状态 
                            $insertApprovedIds[] = $row->FID;
                        }
                    }
                }
                else{
                    $str1 = md5($param['id'] . $param['kingdee_inbound_type'] . $param['kingdee_contract_id'] . $param['supplier_id'] . $param['transaction_type'] . $param['kingdee_biz_type'] . $param['kingdee_base_status'] . $param['audit_time'] . $param['kingdee_code'] . $param['last_update_time']);
                    $str2 = md5($existObj['id'] . $existObj['kingdee_inbound_type'] . $existObj['kingdee_contract_id'] . $existObj['supplier_id'] . $existObj['transaction_type'] . $existObj['kingdee_biz_type'] . $existObj['kingdee_base_status'] . $existObj['audit_time'] . $existObj['kingdee_code'] . $existObj['last_update_time']);

                    //存在且MD5值不一样则更新
                    if($str1 != $str2){
                        // foreach($param as $key=>$value){
                        //     if($key == 'inbound_code' && $existObj['inbound_code'] == $value){
                        //         //inbound_code如果没有变化，跳过该字段
                        //         continue;
                        //     }
                        //     $existObj[$key] = $value;
                        // }
                        // $existObj->save();

                        $scmInbound->updateByKingdeeCode($param, $row->FNumber);

                        //如果状态有发生变更
                        if($param['kingdee_base_status'] == 4){
                            //状态从 新增、保存、提交 状态更新至 【审核】状态 
                            if($existObj['kingdee_base_status'] == 0 || $existObj['kingdee_base_status'] == 1 || $existObj['kingdee_base_status'] == 2){
                                $updateApprovedIds[] = $row->FID;
                            }
                        }
                        else if($param['kingdee_base_status'] == 0 || $param['kingdee_base_status'] == 1 || $param['kingdee_base_status'] == 2){
                            //状态从【审核】状态更新至 新增、保存、提交状态 
                            if($existObj['kingdee_base_status'] == 4){
                                $updateUnApprovedIds[] = $row->FID;
                            }
                        }
                        else if($param['kingdee_base_status'] == 3){
                            //状态从【审核】状态更新至 【作废】状态 
                            if($existObj['kingdee_base_status'] == 4){
                                $updateCanceldIds[] = $row->FID;
                            }
                        }
                    }
                }
            }

            //批量插入数据
            $i = 0;
            $index = 0;
            $parameters = [];
            foreach($params as $param){
                $i++;
                $index++;
                $parameters[] = $param;
                if($i >= 100 || $index == count($params)){
                    $scmInbound->insertMany($parameters);
                    $i = 0;
                    $parameters = [];
                }
            }

            //同步接口
            if($type == 'init'){
                $this->syncInit();
            }
            else{
                if(!empty($insertApprovedIds)){
                    $this->syncAdd($insertApprovedIds);
                }
                if(!empty($updateApprovedIds)){
                    $this->syncUpdateForAudit($updateApprovedIds);
                }
                if(!empty($updateUnApprovedIds)){
                    $this->syncUpdateForUnAudit($updateUnApprovedIds);
                }
                if(!empty($updateCanceldIds)){
                    $this->syncUpdateForCancel($updateCanceldIds);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步入库信息异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    //初始化同步
    private function syncInit(){
        //Log::info('========syncInit==========');
        $response = Http::get($this->baseurl . '/jeecg-boot/bizInbound/syncInit?apiKey=' . $this->apikey);
        if ($response->successful()) {
            Log::info('========syncInit successful==========');
            $json = $response->json(); // 假设返回的是 JSON
            //Log::info('========syncInit json==========' . var_export($json, true));
        }
        //Log::info('========syncInit status==========' . $response->status());
    }

    //新增同步
    private function syncAdd($ids){
        Log::info('========syncAdd==========' . join(",", $ids));
        $response = Http::post($this->baseurl . '/jeecg-boot/bizInbound/syncAdd', [
            'apiKey' => $this->apikey,
            'idList' => $ids
        ]);
        
        $status = "fail";
        $json = $response->json(); // 假设返回的是 JSON
        if ($response->successful() && $json['code'] == 200 && $json['success']) {
            Log::info('========syncAdd successful==========');
            $status = "success";
        }

        ScmSyncRecord::create([
            "ids" => join(",", $ids),
            "type" => "syncAdd",
            "status" => $status,
            "result" => json_encode($json, JSON_UNESCAPED_UNICODE)
        ]);
    }

    //已审核数据更新同步
    private function syncUpdateForAudit($ids){
        Log::info('========syncUpdateForAudit==========' . join(",", $ids));
        $response = Http::post($this->baseurl . '/jeecg-boot/bizInbound/syncUpdateForAudit', [
            'apiKey' => $this->apikey,
            'idList' => $ids
        ]);

        $status = "fail";
        $json = $response->json(); // 假设返回的是 JSON
        if ($response->successful() && $json['code'] == 200 && $json['success']) {
            Log::info('========syncUpdateForAudit successful==========');
            $status = "success";
        }

        ScmSyncRecord::create([
            "ids" => join(",", $ids),
            "type" => "syncUpdateForAudit",
            "status" => $status,
            "result" => json_encode($json, JSON_UNESCAPED_UNICODE)
        ]);
    } 

    //反审核数据更新同步
    private function syncUpdateForUnAudit($ids){
        Log::info('========syncUpdateForUnAudit==========' . join(",", $ids));
        $response = Http::post($this->baseurl . '/jeecg-boot/bizInbound/syncUpdateForUnAudit', [
            'apiKey' => $this->apikey,
            'idList' => $ids
        ]);
        
        $status = "fail";
        $json = $response->json(); // 假设返回的是 JSON
        if ($response->successful() && $json['code'] == 200 && $json['success']) {
            Log::info('========syncUpdateForUnAudit successful==========');
            $status = "success";
        }

        ScmSyncRecord::create([
            "ids" => join(",", $ids),
            "type" => "syncUpdateForUnAudit",
            "status" => $status,
            "result" => json_encode($json, JSON_UNESCAPED_UNICODE)
        ]);
    }

    //作废数据更新同步
    private function syncUpdateForCancel($ids){
        Log::info('========syncUpdateForCancel==========' . join(",", $ids));
        $response = Http::post($this->baseurl . '/jeecg-boot/bizInbound/syncUpdateForCancel', [
            'apiKey' => $this->apikey,
            'idList' => $ids
        ]);
        
        $status = "fail";
        $json = $response->json(); // 假设返回的是 JSON
        if ($response->successful() && $json['code'] == 200 && $json['success']) {
            Log::info('========syncUpdateForCancel successful==========');
            $status = "success";
        }
        ScmSyncRecord::create([
            "ids" => join(",", $ids),
            "type" => "syncUpdateForCancel",
            "status" => $status,
            "result" => json_encode($json, JSON_UNESCAPED_UNICODE)
        ]);
    }

    /**
     * 同步入库明细
     */
    public function syncInboundDetail($mysql_scm, $sqlsrv)
    {
        try {
            $timestamp1 = time() - 7 * 24 * 60 * 60;
            $timestamp2= time();
            // $startDate = "2025-09-01";
            // $endDate = "2025-09-16";
            // $timestamp1 = strtotime($startDate);
            // $timestamp2 = strtotime($endDate);
            $compareStartDate = date("Y-m-d H:i:s", $timestamp1);
            $compareEndDate = date("Y-m-d H:i:s", $timestamp2);
            $scmInboundDetail = (new ScmInboundDetail())->setConnection($mysql_scm);
            $scmPurchaseRequisitionDetail = (new ScmPurchaseRequisitionDetail())->setConnection($mysql_scm);
            $scmOrder = (new ScmOrder())->setConnection($mysql_scm);
            $scmUnitRelation = (new ScmUnitRelation())->setConnection($mysql_scm);
            $hqMaterial = (new HqMaterial())->setConnection($sqlsrv);
            $hqTransactionType = (new HQTransactionType())->setConnection($sqlsrv);
            $hqInbound = (new HQInbound())->setConnection($sqlsrv);
            $hqMeasureUnit = (new HQMeasureUnit())->setConnection($sqlsrv);
            $datalist = HQInboundDetail::on($sqlsrv)->select(["FParentID", "FUnitID", "CFWzsqbh", "FPurOrderNumber", "FMaterialID", "CFFylxID", "FOutLocationID", "FOutWarehouseID", "FLocationID", "FWarehouseID", "FBaseStatus", "FQty", "FID", "FBizDate"])
                ->where("FBizDate", ">=", $compareStartDate)
                ->where("FBizDate", "<=", $compareEndDate)
                ->orderBy("FBizDate", "DESC")
                ->get();

            $params = [];//插入的数据
            foreach($datalist as $row){
                //本地采购系统是否存在
                $hqInboundRow = $hqInbound->findRowById($row->FParentID);
                $hqTransactionTpyeRow = $hqTransactionType->findRowById($hqInboundRow->FTransactionTypeID);
                $hqMeasureUnitRow = $hqMeasureUnit->findRowById($row->FUnitID);
                $scmUnitRelationRow = $scmUnitRelation->findRowByKingdeeUnit($hqMeasureUnitRow->FNumber);
                $scmPurchaseRequisitionDetailRow = $row->CFWzsqbh ? $scmPurchaseRequisitionDetail->findRowByWzsqbh($row->CFWzsqbh) : null;
                $scmOrderRow = $row->FPurOrderNumber ? $scmOrder->findRowKingdeeCode($row->FPurOrderNumber) : null;
                $hqMaterialRow = $row->FMaterialID ? $hqMaterial->findRowById($row->FMaterialID) : null;
                $param = array(
                    'kingdee_wzsqbh' => $row->CFWzsqbh,
                    'kingdee_expense_type_id' => $row->CFFylxID,
                    'kingdee_biz_date' => date("Y-m-d H:i:s", strtotime($row->FBizDate)),
                    'kingdee_qty' => $row->FQty,
                    'out_location' => $row->FOutLocationID,
                    'out_warehouse' => $row->FOutWarehouseID,  
                    'location' => $row->FLocationID,
                    'warehouse' => $row->FWarehouseID,
                    'kingdee_base_status' => $row->FBaseStatus,
                    'pur_order_number' => $row->FPurOrderNumber,
                    'order_id' => $scmOrderRow ? $scmOrderRow->id : '',
                    'requisition_detail_id' => $scmPurchaseRequisitionDetailRow ? $scmPurchaseRequisitionDetailRow->id : "",
                    'inbound_unit' => $scmUnitRelationRow ? $scmUnitRelationRow->unit : "",
                    'kingdee_unit' => $scmUnitRelationRow ? $scmUnitRelationRow->unit : "",
                    'material_id' => $hqMaterialRow ? $hqMaterialRow->FNumber : "",
                    'kingdee_parent' => $row->FParentID,
                    'inbound_id' => $row->FParentID,
                    'sync_time' => date("Y-m-d H:i:s")
                );

                //更新状态
                if($param['kingdee_base_status'] == 3){
                    $param['is_cancel'] = 1;
                }
                else{
                    $param['is_cancel'] = 0;
                }

                //事务类型是 项目采购 (编码 104) 的情况下，不更新该字段
                if($hqTransactionTpyeRow->FNumber != "104"){
                    $param['inbound_quantity'] = $row->FQty;
                }
                else{
                    $param['inbound_quantity'] = 0;
                }

                $existObj = $scmInboundDetail->findRowById($row->FID);
                if(!$existObj){
                    $param['id'] = $row->FID;

                    //插入数据
                    $params[] = $param;
                    //$scmInboundDetail->insertOne($param); //改成批量插入数据
                }
                else{
                    $str1 = md5($param['material_id'] . $param['kingdee_wzsqbh'] . $param['kingdee_expense_type_id'] . $param['kingdee_biz_date'] . $param['kingdee_qty'] . $param['location'] . $param['warehouse'] . $param['kingdee_base_status'] . $param['pur_order_number'] . $param['order_id'] . $param['requisition_detail_id']);
                    $str2 = md5($existObj['material_id'] . $existObj['kingdee_wzsqbh'] . $existObj['kingdee_expense_type_id'] . $existObj['kingdee_biz_date'] . $existObj['kingdee_qty'] . $existObj['location'] . $existObj['warehouse'] . $existObj['kingdee_base_status'] . $existObj['pur_order_number'] . $existObj['order_id'] . $existObj['requisition_detail_id']);

                    //存在且MD5值不一样则更新
                    if($str1 != $str2){
                        $scmInboundDetail->updateById($param, $row->FID);
                    }
                }
            }

            //插入数据
            $i = 0;
            $index = 0;
            $parameters = [];
            foreach($params as $param){
                $i++;
                $index++;
                $parameters[] = $param;
                if($i >= 100 || $index == count($params)){
                    $scmInboundDetailNew = (new ScmInboundDetail())->setConnection($mysql_scm);
                    $scmInboundDetailNew->insertMany($parameters);
                    $i = 0;
                    $parameters = [];
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步入库详情信息异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步事务类型
     */
    public function syncTransactionType($mysql_scm, $sqlsrv)
    {
        try {
            $scmTransactionType = (new ScmTransactionType())->setConnection($mysql_scm);
            $datalist = HQTransactionType::on($sqlsrv)->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmTransactionType->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'code' => $row->FNumber,
                        'name' => $row->FName_L2,
                        'bill_type_id' => $row->FBillTypeID,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmTransactionType->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步事务类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步费用类型
     */
    public function syncExpenseType($mysql_scm, $sqlsrv)
    {
        try {
            $scmExpenseType = (new ScmExpenseType())->setConnection($mysql_scm);
            $datalist = HQExpenseType::on($sqlsrv)->orderBy("FID", "DESC")->get();
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmExpenseType->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'code' => $row->FNumber,
                        'name' => $row->FName_L2,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmExpenseType->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步费用类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同单据类型
     */
    public function syncBillType($mysql_scm, $sqlsrv)
    {
        try {
            $scmBillType = (new ScmBillType())->setConnection($mysql_scm);
            $datalist = HQBillType::on($sqlsrv)->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmBillType->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'code' => $row->FNumber,
                        'name' => $row->FName_L2,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmBillType->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步单据类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步业务类型
     */
    public function syncBizType($mysql_scm, $sqlsrv)
    {
        try {
            $scmBizType = (new ScmBizType())->setConnection($mysql_scm);
            $datalist = HQBizType::on($sqlsrv)->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmBizType->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'code' => $row->FNumber,
                        'name' => $row->FName_L2,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmBizType->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步业务类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步仓库
     */
    public function syncWarehouse($mysql_scm, $sqlsrv)
    {
        try {
            $scmWarehouse = (new ScmWarehouse())->setConnection($mysql_scm);
            $datalist = HQWarehouse::on($sqlsrv)->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmWarehouse->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'warehouse_code' => $row->FNumber,
                        'warehouse_name' => $row->FName_L2,
                        'control_unit_id' => $row->FControlUnitID,
                        'storage_org_id' => $row->FStorageOrgID,
                        'status' => $row->FWhState,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmWarehouse->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步仓库类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步库区
     */
    public function syncLocation($mysql_scm, $sqlsrv)
    {
        try {
            $scmLocation = (new ScmLocation())->setConnection($mysql_scm);
            $datalist = HQLocation::on($sqlsrv)->orderBy("FID", "DESC")->get();
            foreach($datalist as $row){
                //本地采购系统是否存在
                $newId = $row->FID . "_" . $row->FNumber;
                $existObj = $scmLocation->findRowById($newId);
                if(!$existObj){
                    $param = array(
                        'id' => $newId,
                        'location_code' => $row->FNumber,
                        'location_name' => $row->FName_L2,
                        'warehouse_id' => $row->FWarehouseID,
                        'status' => $row->FState,
                        'kingdee_id' => $row->FID
                    );

                    //插入数据
                    $scmLocation->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步库区类型异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    /**
     * 同步供应商
     */
    public function syncSupplier($mysql_scm, $sqlsrv)
    {
        try {
            $scmSupplier = (new ScmSupplier())->setConnection($mysql_scm);
            $datalist = HQSupplier::on($sqlsrv)->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在，只更新，不插入
                $existObj = $scmSupplier->findRowByName($row->FName_L2);
                if($existObj){
                    $existObj->kingdee_code = $row->FNumber;
                    $existObj->kingdee_id = $row->FID;

                    if($existObj->code && $row->FNumber != $existObj->code){
                        $existObj->code = $row->FNumber;
                    }

                    //更新数据
                    $existObj->save();
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步供应商异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

}